package com.teamwechat.controller;

import cn.hutool.json.JSONUtil;
import com.teamwechat.common.utils.R;
import com.teamwechat.config.shiro.JwtUtil;
import com.teamwechat.exception.TeamsException;
import com.teamwechat.mapper.TbUserMapper;
import com.teamwechat.pojo.Contacts;
import com.teamwechat.pojo.TbUser;
import com.teamwechat.pojo.vo.LoginFormVo;
import com.teamwechat.service.UserService;
import com.teamwechat.vo.RegisterFormVo;
import com.teamwechat.vo.SearchMembersFormVo;
import com.teamwechat.vo.SearchUserGroupByDeptFormVo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/user")
@ApiModel("用户模块Web接口")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${teams.jwt.cache-expire}")
    private int cacheExpire;

    @PostMapping("/register")
    @ApiOperation("注册用户")
    public R register (@Valid @RequestBody RegisterFormVo formVo){
        //1.注册用户,返回用户朱主键
        int userId = userService.registerUser(formVo.getRegisterCode(), formVo.getCode(), formVo.getNickname(), formVo.getPhoto());
        //2.通过用户主键生成 访问令牌
        String token = jwtUtil.createToken(userId);
        //3.将令牌缓存到redis
        saveCacheToken(token,userId);
        //4.通过用户id查询用户权限
        Set<String> permsSet = userService.searchUserPermissions(userId);
        //5.响应给前端页面 令牌 及用户权限
        return R.ok("用户注册成功").put("token",token).put("permission",permsSet);
    }

    private void saveCacheToken(String token, int userId) {
        redisTemplate.opsForValue().set(token,userId+"",cacheExpire);
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public R login(@Valid@RequestBody LoginFormVo form){

        Integer id = userService.login(form.getCode());
        String token = jwtUtil.createToken(id);
        Set<String> permsSet = userService.searchUserPermissions(id);
        saveCacheToken(token,id);
        return R.ok("用户登录成功").put("token",token).put("permission",permsSet);
    }

    @GetMapping("/searchUserSummary")
    @ApiOperation("查询用户摘要信息")
    public R searchUserSummary(@RequestHeader("token")String token){
        int userId = jwtUtil.getUserId(token);
        HashMap hashMap = userService.searchUserSummary(userId);
        return R.ok().put("result",hashMap);
    }



    @PostMapping("/searchUserGroupByDept")
    @ApiOperation("查询员工列表，按照部门分组排列")
    @RequiresPermissions(value = {"ROOT","EMPLOYEE:SELECT"},logical = Logical.OR)
    public R searchUserGroupByDept(@Valid @RequestBody SearchUserGroupByDeptFormVo form){
        ArrayList<HashMap> list=userService.searchUserGroupByDept(form.getKeyword());
        return R.ok().put("result",list);
    }

    @PostMapping("/searchMembers")
    @ApiOperation("查询成员")
    @RequiresPermissions(value = {"ROOT", "MEETING:INSERT", "MEETING:UPDATE"},logical = Logical.OR)
    public R searchMembers(@Valid @RequestBody SearchMembersFormVo form){
        if(!JSONUtil.isJsonArray(form.getMembers())){
            throw new TeamsException("members不是JSON数组");
        }
        List param=JSONUtil.parseArray(form.getMembers()).toList(Integer.class);
        ArrayList list=userService.searchMembers(param);
        return R.ok().put("result",list);
    }

//    @GetMapping("/SearchUserinfomation")
//    @ApiOperation("查询用户详细信息")
//    public R SearchUserinfomation(@RequestHeader("token")String token){
//        int userId = jwtUtil.getUserId(token);
//        HashMap hashMap = userService.SearchUserinfomation(userId);
//        return R.ok().put("result",hashMap);
//    }

    @GetMapping("/SearchUserinfomation")
    @ApiOperation("查询用户详细信息")
    public R SearchUserinfomation(@RequestHeader("token")String token){
        int userId = jwtUtil.getUserId(token);
        HashMap hashMap = userService.SearchUserinfomation(userId);
        return R.ok().put("result",hashMap);
    }

    @GetMapping("/searchcontacts")
    @ApiOperation("通讯录用户信息")
    public R searchcontacts(@RequestHeader("token") String token){
        int userId=jwtUtil.getUserId(token);
        HashMap map=new HashMap();

        ArrayList list=userService.searchcontacts(map);
        return R.ok().put("result",list);
    }

    @PostMapping("/addtel")
    @ApiOperation("添加通讯录用户")
    @RequiresPermissions(value = {"ROOT","EMPLOYEE:SELECT"},logical = Logical.OR)
    public R addtel(){
        HashMap map = new HashMap();
        ArrayList<HashMap> list=userService.addtel(map);
        return R.ok().put("result",list);
    }

    @PostMapping("addtell")
    public R insert(@RequestBody Contacts contacts){                   //接受实体类的对象
        tbUserMapper.insert(contacts);
        return R.ok("添加成功");
    }

    @GetMapping("/{id}")
    @ResponseBody
    public TbUser getUserById(@PathVariable("id") Integer id) {
        return tbUserMapper.getUserById(id);
    }




}